package com.rpcdemo.util;

import java.io.*;

/**
 * @ClassName SeriaUtil
 * @Description TODO
 * @Author: XMK
 * @Date: 2020/10/14 10:41
 * @Version: 1.0
 */
public class SeriaUtil {

    public static byte[] encode(Object msg) {

//            ObjectMapper objectMapper = new ObjectMapper();
//            byte[] byteBody = objectMapper.writeValueAsBytes(msg);

//            byte[] byteBody = JSON.toJSONBytes(msg);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] byteBody = baos.toByteArray();

        return byteBody;
    }

    public static Object decode(byte[] bytes) {


//            ObjectMapper objectMapper = new ObjectMapper();
//            ReqHeader reqHeader = objectMapper.readValue(bytes, ReqHeader.class);

//            ReqHeader reqHeader = JSON.parseObject(bytes, ReqHeader.class);

        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = null;
        Object obj = null;
        try {
            ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return obj;
    }


}
